package com.doradance.app.home;


import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.search.core.PoiInfo;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.doradance.R;
import com.doradance.account.ParamKey;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.XCRoundRectImageView;
import com.doradance.app.activity.ActivityDetailActivity;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.ActivityEntity;
import com.doradance.entity.BannerEntity;
import com.doradance.entity.IndexEntity;
import com.doradance.entity.OrgTypeEntity;
import com.doradance.entity.RefreshHome;
import com.doradance.entity.UpdataDetailEntity;
import com.google.gson.TypeAdapter;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.LoadState;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.framework.httprequest.responsecallbacks.ListDataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.microedition.khronos.opengles.GL;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeSubFragment extends SwipeListFragment implements View.OnClickListener{
    private ConvenientBanner mConvenientBanner;
    private RecyclerView recButtons;
    private HomeStarAdapter homeStarAdapter;
    private ImageView ivIndexHot;
    private List<IndexEntity.FreeCoursesBean> free_courses1;
    RelativeLayout rlFreeOne;
    RelativeLayout rlFreeTwo;
    LinearLayout llFree;
    XCRoundRectImageView ivFreeOne;
    XCRoundRectImageView ivFreeTwo;
    TextView tvFreeOne;
    TextView tvFreeTwo;
    TextView tvNumOne;
    TextView tvNumTwo;
    RelativeLayout ivFreeMore;
    RelativeLayout rlActivityMore;
    RelativeLayout rlRecommenedMore;
    public HomeSubFragment() {
        // Required empty public constructor
    }

    @Override
    public void onResume() {
        super.onResume();
        mConvenientBanner.startTurning(5000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mConvenientBanner.stopTurning();
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        getData().clear();
        startLoading();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        startLoading();
        setPullToRefreshEnable(false);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshHome refreshEvent) {
        IndexEntity o = refreshEvent.o;
        getBannerData(o.getBanners());
        getAdapter().getData().clear();
        getAdapter().getData().addAll(o.getRcmd_courses());
        getStarType(o.getStar_students());
        setHotIv(o.getActivity_cover());
        setFree(o.getFree_courses());
        getAdapter().notifyDataSetChanged();
        setState(CompState.DATA);
        hideRefreshView();
        ivIndexHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HotActivityActivity.start(getActivity());
            }
        });
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return  new HomeListAdapter(getContext());
    }
    @Override
    public void onStartLoading() {
        getListData();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long itemId) {
        super.onItemClick(arg0, arg1, position, itemId);
        IndexEntity.RcmdCoursesBean activityEntity = (IndexEntity.RcmdCoursesBean)getData().get(position);
        CoursesDetailActivity.start(getActivity(),activityEntity.getId());
    }

    private void getListData() {
        MyHttpRequest request = new MyHttpRequest(getContext());
        UrlParams urlParams = new UrlParams();
        request.get(UrlCenter.INDEX, urlParams, new DataRequestListener<IndexEntity>(IndexEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(IndexEntity o) {
                super.onSuccess(o);
                getBannerData(o.getBanners());
                getAdapter().getData().addAll(o.getRcmd_courses());
                getStarType(o.getStar_students());
                setHotIv(o.getActivity_cover());
                setFree(o.getFree_courses());
                getAdapter().notifyDataSetChanged();
                ivIndexHot.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    HotActivityActivity.start(getActivity());
                    }
                });
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void setFree(List<IndexEntity.FreeCoursesBean> free_courses) {

        free_courses1 = free_courses;
        if(free_courses.size()==0){
            llFree.setVisibility(View.GONE);
        }else if(free_courses.size()==1){
            rlFreeOne.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(free_courses.get(0).getCover()).asBitmap().into(ivFreeOne);
            tvFreeOne.setText(free_courses.get(0).getName());
            tvNumOne.setText(free_courses.get(0).getLearning_count()+"");
        } else{
            rlFreeOne.setVisibility(View.VISIBLE);
            rlFreeTwo.setVisibility(View.VISIBLE);

            Glide.with(getActivity()).load(free_courses.get(0).getCover()).asBitmap().dontAnimate()
                    .placeholder(R.mipmap.init_logo).into(ivFreeOne);
            tvFreeOne.setText(free_courses.get(0).getName());
            tvNumOne.setText(free_courses.get(0).getLearning_count()+"");

            Glide.with(getActivity()).load(free_courses.get(1).getCover()).asBitmap().dontAnimate()
                    .placeholder(R.mipmap.init_logo).into(ivFreeTwo);
            tvFreeTwo.setText(free_courses.get(1).getName());
            tvNumTwo.setText(free_courses.get(1).getLearning_count()+"");
        }
        rlFreeOne.setOnClickListener(this);
        rlFreeTwo.setOnClickListener(this);
        ivFreeMore.setOnClickListener(this);
        rlActivityMore.setOnClickListener(this);
        rlRecommenedMore.setOnClickListener(this);
    }


    //设置热门图片
    private void setHotIv(String url) {
        Glide.with(getActivity()).load(url).dontAnimate()
                .placeholder(R.mipmap.init_logo).into(ivIndexHot);
    }

    @Override
    public View createHeaderView(LayoutInflater inflater) {
        clearDecorations();
        View headerView = inflater.inflate(R.layout.home_header, null);
        initHeadView(headerView);
        return headerView;
    }

    private void initHeadView(View view) {
        mConvenientBanner = (ConvenientBanner) view.findViewById(R.id.convenientBanner);
        recButtons = (RecyclerView) view.findViewById(R.id.recButtons);
        rlFreeOne = (RelativeLayout) view.findViewById(R.id.rl_free_one);
        rlFreeTwo = (RelativeLayout) view.findViewById(R.id.rl_free_two);
        llFree = (LinearLayout) view.findViewById(R.id.ll_free);
//        view.findViewById(R.id.rl_free_bg_one).setAlpha(0.7f);
        ivFreeOne = (XCRoundRectImageView) view.findViewById(R.id.iv_free_one);
        ivFreeTwo = (XCRoundRectImageView) view.findViewById(R.id.iv_free_two);
//        view.findViewById(R.id.ll_free_one).setAlpha(0.7f);
//        view.findViewById(R.id.ll_free_two).setAlpha(0.7f);
        tvFreeOne = (TextView) view.findViewById(R.id.tv_free_one);
        tvFreeTwo = (TextView) view.findViewById(R.id.tv_free_two);
        tvNumOne = (TextView) view.findViewById(R.id.tv_num_one);
        tvNumTwo = (TextView) view.findViewById(R.id.tv_num_two);
        ivFreeMore = (RelativeLayout)view.findViewById(R.id.iv_free_more);

        rlRecommenedMore = (RelativeLayout) view.findViewById(R.id.rl_recommened_more);

        rlActivityMore = (RelativeLayout) view.findViewById(R.id.rl_activity_more);
        homeStarAdapter = new HomeStarAdapter(getContext());
        recButtons.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recButtons.setAdapter(homeStarAdapter);

        ivIndexHot = (ImageView) view.findViewById(R.id.iv_index_hot);
//
    }

    //明星学员
    private void getStarType(List<IndexEntity.StarStudentsBean> o) {
                homeStarAdapter.getData().clear();
                homeStarAdapter.getData().addAll(o);
                homeStarAdapter.notifyDataSetChanged();
    }

    private void setBannerData(final List<IndexEntity.BannersBean> bannerData) {
        mConvenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, bannerData).setPageIndicator(new int[]{R.mipmap.icon_nav_n, R.mipmap.icon_nav_p})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
                mConvenientBanner.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        String type = bannerData.get(position).getType();
                        if(type.equals("course")){
                            int targetId = bannerData.get(position).getTarget_id();
                            CoursesDetailActivity.start(getActivity(),targetId);
                        }else if(type.equals("activity")){
                            int targetId = bannerData.get(position).getTarget_id();
                            ActivityDetailActivity.start(getActivity(),targetId);
                        }else{
                            String href = bannerData.get(position).getHref();
                            BannerDetilActivity.start(getActivity(),href);
                        }
                    }
                });
                }
    /**
     * 获取banner数据
     */
    private void getBannerData(List<IndexEntity.BannersBean> bannerEntity) {
        setBannerData(bannerEntity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
          case R.id.rl_free_one:
              CoursesDetailActivity.start(getActivity(),free_courses1.get(0).getId());
              break;
            case R.id.rl_free_two:
                CoursesDetailActivity.start(getActivity(),free_courses1.get(1).getId());
                break;
            case R.id.iv_free_more:
                FreeListActivity.start(getActivity());
                break;
            case R.id.rl_activity_more:
                HotActivityActivity.start(getActivity());
                break;
            case R.id.rl_recommened_more:
                MoreVideoActivity.start(getActivity(),-2);
                break;
        }
    }



}